

/*********CategoryCombobox栏目**********************************************/
CategoryCombobox = Ext.extend(Ext.form.ComboBox, {
	constructor : function() {
		CategoryCombobox.superclass.constructor.call(this, {
			hiddenName : 'cid',
			fieldLabel : '新闻栏目',
			displayField : 'ctitle',
			valueField : 'cid',
			triggerAction : 'all',
			allowBlank : false,
			modal : "remote",
			editable : false,
			loadingText : "正在读取栏目信息",
			emptyText : "请务必选择新闻所在栏目",
			blankText : "发布新闻，请先指定所属栏目",
			store : new Ext.data.Store({
						autoLoad : true,
						url :CategoryListURL_GLOBAL,
						reader : new Ext.data.ArrayReader({}, ["cid", "ctitle"])
					}),
			listeners:{
						"select":{
									fn:function(){//用于formpanel中，设置隐藏字段ctitle的值
							        	this.ownerCt.getForm().findField("ctitle").setValue(this.ownerCt.getForm().findField("cid").getRawValue());    
									},
									scope:this
								}
						}
		});
	}
});

/*********newsInfoForm窗口的表单********0*0**************************************/
NewsInfoForm = Ext.extend(Ext.form.FormPanel, {


	categoryCombobox : null,
	constructor : function() {
		this.categoryCombobox =new CategoryCombobox();
		NewsInfoForm.superclass.constructor.call(this, {
			frame : true,
			labelWidth : 60,
			//renderTo : Ext.getBody(),
			defaultType : "textfield",
			defaults : {anchor : "98%"},
			layout : "form",
			items : [{xtype : "hidden",name : 'nid'},
					{xtype : 'hidden',name : 'ndate'}, 
					{xtype : 'hidden',name : 'nhref'},
					{xtype : 'hidden',name : 'nclicked'},
					{xtype : 'hidden',name : 'ctitle'},
					{xtype : 'hidden',name : 'ntoplevel'},
					//{xtype : 'hidden',name : 'nvisiable'}, 
					{name : "ntitle",fieldLabel : "新闻标题"},
					this.categoryCombobox,
					{name : "nsummary",xtype : "textarea",fieldLabel : "新闻摘要"}, 
					{name : "ncontent",fieldLabel : "新闻内容",height : 315,xtype : 'fckeditor'},
					{
						xtype : "panel",
						layout : "column",
						items : [{
									columnWidth : .3,
									layout : 'form',
									items : [{//id : "nvisiable",
												fieldLabel : "是否发布",
												displayField : "isvisiable",
												valueField:"nvisiable",
												triggerAction : "all",
												editable:false,
												//selectOnFocus : true, 
												name: "isvisiable",
												hiddenName : "nvisiable",
												value:true,//默认是发布状态
												xtype : "combo",
												mode : 'local',
												store : new Ext.data.SimpleStore(
														{
															data : [["是",true],
																	["否",false]],
															fields : [{name:"isvisiable"},{name:"nvisiable",type:"boolean"}]
														})
											}]
								}, {
									columnWidth : .3,
									layout : 'form',
									items : [{
											    name : "istoplevel",
												fieldLabel : "置最高顶",
												displayField : "istoplevel",
												triggerAction : "all",
												mode : 'local',
												xtype : "combo",
												store : new Ext.data.SimpleStore(
														{
															data : [["是"],
																	["否"]],
															fields : ["istoplevel"]
														})
											}]

								},
								{
													columnWidth:.4,
													layout:'form',
													items:[{
														name:'nwriter',
														xtype:"textfield",
														fieldLabel:"news writer",
														value:"无名氏"}]
													}]
					}]
		});
	},
	getValues:function(){
		if(this.getForm().isValid())
		   return this.getForm().getValues();//);new Ext.data.Record(
		else
			throw Error("表单认证没有成功,请填写必要的信息");
		   // alert("表单认证没有成功");
		},
	setValues:function(_r){
		this.getForm().loadRecord(_r);
		this.getForm().items.each(function(f){
					if(f.getName()=="ncontent"){
						f.originalValue = _r.data["ncontent"];
				 }else
				 {
					 f.originalValue=f.getValue();
				 }
		});
		// 对于编辑新闻窗口加载数据时，将istoplevel字段的值设置成否，表示保持原先置顶等级
		//alert("否")
		this.getForm().findField("istoplevel").originalValue="否";
		this.getForm().findField("istoplevel").setValue("否");
	}
});

/*********BasicInfoWindow基本窗口********************************************/
BasicInfoWindow = Ext.extend(Ext.Window, {
			formPanel:null,
			constructor : function() {
					//if(_cfg!=null)
						
				    this.formPanel=new NewsInfoForm();
					BasicInfoWindow.superclass.constructor.call(this, {
						width:850,
						height:550,						
						constrainHeader:true,//不可越过浏览器顶端
						items:this.formPanel,
						closeAction:"close_Ctrl",
						buttonAlign:"center",
						buttons:[{
									text:"确定",
									handler:this.onSubmitClick,
									scope:this
								},{text:"取消",
									handler:this.onCancelClick,
									scope:this}]
					});
					this.addEvents("submit");
					//Ext.apply(this,_cfg);
				},
				close_Ctrl:function(){
					
					this.formPanel.getForm().items.each(function(f){
							 f.originalValue="";
					});this.formPanel.getForm().reset();
					//alert(this.formPanel.getForm().findField("cid").getValue());
					//this.formPanel.getForm().findField("ncontent").destroy();
					//this.removeAll(true);
					this.hide();
		            //this.destroy() ;
				},
				onSubmitClick:function(){
					try{
						this.fireEvent("submit",this,this.getValues());//不用formPanel中的getValues()，应该是各自window中的getValue（）；
						
					}catch(_err){alert(_err);}//catch错误，例如表单认证没有成功
				},
				onCancelClick:function(){
					this.close_Ctrl();
				},
				onbeforeShow:function(){},//让子类重写
				getValues:function(){}		//让子类重新写
})

/*********InsertNewsInfoWindow添加新闻的窗口*********************************/
InsertNewsInfoWindow=Ext.extend(BasicInfoWindow,{
	title:"添加新闻",
	onbeforeShow:function(){	//show窗口之前初始化nddate,ntoplevel,nclicked字段
						var ndate =new Date();
						this.formPanel.getForm().findField("ndate").setValue(ndate);//添加时间日期
						this.formPanel.getForm().findField("ntoplevel").setValue(ndate.getTime());//置最高等级
						this.formPanel.getForm().findField("nclicked").setValue(1);//置点击数量默认为1
						},
	getValues:function(){
						try{//catch异常再次往外抛出
						var oJson =this.formPanel.getValues();
						delete oJson.istoplevel;
						}catch(_err){throw Error("表单认证没有成功,请填写必要的信息"); }//再次向外抛出异常
						return oJson;
						}
});

/*********UpdateNewsInfoWindow更新新闻的窗口*********************************/
UpdateNewsInfoWindow=Ext.extend(BasicInfoWindow,{
	title:"更新新闻",
	load:function(_r){
		this.formPanel.setValues(_r);
	},
	getValues:function(){
		if(!this.formPanel.getForm().isValid())
		   throw Error("表单认证没有成功");
		else{
			var oJson={};       
			this.formPanel.getForm().items.each(function(f) {
						            if (f.isDirty()) {
						            	var temp={};
						            	temp[f.getName()]=f.getValue();
						            		Ext.apply(oJson,temp);
						           		 }
						       	 }
						       	 
			);
			//在传送给grid前把 修改过的数据对象去除istoplevel属性，
			if(oJson.istoplevel)
				delete oJson.istoplevel;
			return oJson;
		}
	}
});

/*********NewsManageGridPanel新闻管理GridPanel*******************************/
NewsManageGridPanel = Ext.extend(Ext.grid.EditorGridPanel, {
		insertNewsInfoWindow:null,
		updateNewsInfoWindow:null,
		categoryCombobox:null,
		categoryStore:null,
		//CellcategoryCombobox:null,
		inserted:null,
		store:null,
		sm:null,
		constructor : function() {
			this.inserted=[];//在送去后台前先 保存添加的数据
			this.insertNewsInfoWindow=new InsertNewsInfoWindow();
			this.updateNewsInfoWindow=new UpdateNewsInfoWindow();
			this.categoryStore=new Ext.data.Store({
						url : "../admin/getSCategoryList.action",
						reader : new Ext.data.ArrayReader({}, ["cid", "ctitle"])
					});
			this.categoryCombobox = new Ext.form.ComboBox({		//定义combobox组件
										hiddenName : "cid",
										//fieldLabel : "cTitle",
										listWidth:200,
										width:200,
										displayField:"ctitle",
										valueField : "cid",
										triggerAction : "all",
										mode : "remote",
										value:"   全部      ",
										width:70,
										editable : false,
										loadingText : "正在读取栏目信息",
										emptyText : "请务必选择新闻所在栏目",
										blankText : "发布新闻，请先指定所属栏目",
										store : this.categoryStore,
										listeners:{
													"select":{
																fn:this.onSelectedAction,
																scope:this
															}
													}
									});
			//this.CellcategoryCombobox=new CategoryCombobox();
			this.store=new Ext.data.JsonStore({
							url:NewsListURL_GLOBAL,
							baseParams :{categoryid:0},
							root:"data",//categorys数据
							totalProperty  :"totalProperty",//总数
							fields:[
									{name:"nid",mapping:"nid"},//本新闻id
									{name:"cid",mapping:"cid"},//本新闻所在栏目编号
									{name:"ctitle",mapping:"ctitle"},
									{name:"ntitle",mapping:"ntitle"},//本新闻标题
									{name:"nwriter",mapping:"nwriter"},//本新闻作者
									{name:"nclicked",mapping:"nclicked"},//本新闻点击数
									{name:"ntoplevel",mapping:"ntoplevel"},//本新闻置顶等级
									{name:"nvisiable",mapping:"nvisiable",type:"boolean"},//本新闻首页显示boolean值
									{name:"ndate",mapping:"ndate"},//本新闻添加日期
									{name:"nhref",mapping:"nhref"},//本新闻链接
									{name:"ncontent",mapping:"ncontent"}//本新闻内容
									],
							listeners :{//监听store中的update事件，disable/enable保存按钮与categoryCombobox
													"update":{
															fn:this.disableWidget,
															scope:this
													}
											}
			});
			this.store.load({params:{start:0 , limit:5}});
			this.sm=new Ext.grid.CheckboxSelectionModel();
			NewsManageGridPanel.superclass.constructor.call(this,{
				renderTo : Ext.getBody(),
				title : "新闻管理窗口",
				width : 880,
				height : 400,
				store:this.store,
				sm:this.sm,
				tbar : [{
							id:'save',
							text : "保存",
							disabled:true,
							handler:this.onSaveClick,
							scope:this
						},"-",{
							text : "添加",
							handler:this.onInsertButtonClick,
							scope:this
						},"-",{
							text:"编辑",
							handler:this.onUpdateButtonClick,
							scope:this
						},"-",{
							text : "删除"
						},"-","column",this.categoryCombobox],
				columns :[new Ext.grid.RowNumberer(), // 数据序列// 定义列模型
										 this.sm,
					 {
					 	id:"cid",
					 	header:"栏目编号",
					 	dataIndex:"cid"
					 },{
					 	id:"ctitle",
					 	header:"栏目",
					 	dataIndex:"ctitle"/*,
					 	editor:this.CellcategoryCombobox,
					 	renderer:function(value, cellmeta, record, rowIndex, columnIndex, store){
					 		alert(record.data["ctitle"]);
					 		record.data["cid"]=record.data["ctitle"];
					 	return record.data["ctitle"];
					 	}*/
					 	
					 },{
						id : "ntitle",
						header : "标题", // 显示值
						width : 110,
						dataIndex : "ntitle", // 映射到Record中定义的数据行其中一列的逻辑名
						editor : new Ext.grid.GridEditor(new Ext.form.TextField())
					},{
						id : "nwriter",
						header : '新闻作者',//
						dataIndex : "nwriter",
						editor : new Ext.grid.GridEditor(new Ext.form.TextField())
					}, {
						id : "nhref",
						header : "链接",
						width:250,
						dataIndex : "nhref"//,
						//editor : new Ext.grid.GridEditor(new Ext.form.TextField())
					} ,{
						id : "nvisiable",
						header : "首页显示",
						dataIndex : "nvisiable",
						renderer:function(_v){if(_v){//alert("是否发布："+_v);
												return "<span  style='margin-right:10px'>发布</span>";}
												else{//alert("shifou "+_v);
												return "<span  style='margin-right:10px'>尚未发布</span>"}},
						editor : new Ext.grid.GridEditor(new Ext.form.ComboBox({
																		displayField:"isvisiable",
																		valueField:"nnn",
																		triggerAction : "all",
																		mode : "local",
																		store:new Ext.data.SimpleStore({
																						data:[["是",true],["否",false]],
																						fields:["isvisiable","nnn"]
																						})
																			}
																			))
					}, {
						id : "ntoplevel",
						header : "置顶",
						dataIndex:"ntoplevel",
						
						renderer:function(_v){
													//alert("ok");
													return  "<img src='../js/master/images/icon/lightbulb.gif' onclick=javascript:alert(Ext.getCmp('ntoplevel')); >"
													}
					}],
				bbar : new Ext.PagingToolbar({
								store : this.store, // 作为pagingToolbar的数据存储器
								pageSize : 5,
								displayInfo : true,
								displayMsg : "当前显示从{0}条到{1}条,共{2}条",
								emptyMsg : "<span style='color:red;font-style:italic;'>对不起,没有找到数据</span>"
							})
						
			});
			this.insertNewsInfoWindow.on("submit",this.onInsertWinSubmit,this);
			this.updateNewsInfoWindow.on("submit",this.onUpdateWinSubmit,this);
		},
		onSaveClick:function(){		//保存数据到数据库
				var _m = this.getStore().modified ;//m是record类型数组【record】
				
				var _updatedata = [] ;//向服务器发送类似【{}{}】这样的json数组
				
				var _addata = [];//前台添加的数据
				
				for(var _i = 0 ; _i < _m.length ; _i ++){//获取修改的数据
					
					if(_m[_i].get("nid") == "")
					
						continue ;
					
					var _data = {} ;
					
					var _j = "" ;
					
					for(_j in _m[_i].modified)
					
						_data[_j] = _m[_i].get(_j) ;//get the value of named field //json{}对象
				
					_updatedata.push(Ext.apply(_data , {nid:_m[_i].get("nid")})) ;
					
				}
				
				for(var _i = 0 ; _i < this.inserted.length ; _i ++)//获取添加的数据
				
					_addata.push(this.inserted[_i].data) ; //inserted是【record类型】数组，那么insert[i]则是record对象，data这是数据对象（在这是json对象）
				this.inserted=[];
				alert("修改的数据如下：");
				alert(Ext.util.JSON.encode(_updatedata));
				alert("添加的数据如下：");
				alert(Ext.util.JSON.encode(_addata));
					
				this.getStore().commitChanges();//
				Ext.getCmp("save").disable();
				alert("脏数据的原始数据个数为"+this.getStore().modified.length);
		},
		onInsertButtonClick:function(){
			this.insertNewsInfoWindow.show();
		},
		onUpdateButtonClick:function(){
			var _sm=this.getSelectionModel();
			if(_sm.getCount()==0)
				alert("你尚未选定一个新闻记录！");
			else if(_sm.getCount()>1){
				alert("你不能选择多条新闻记录！");
			}else{
				this.updateNewsInfoWindow.show();	
				this.updateNewsInfoWindow.load(_sm.getSelected());				
			}
		},
		onInsertWinSubmit:function(_win,oJson){
			
				/*alert(Ext.util.JSON.encode(this.insertNewsInfoWindow.formPanel.getValues().data));
				this.getStore().add(_r);*/
				_win.close_Ctrl();
				var _r = new Ext.data.Record({
							"nid":"",//本新闻id
							"cid":"",//本新闻所在栏目编号
							"ctitle":"",
							"ntitle":"",//本新闻标题
							"nwriter":"",//本新闻作者
							"nclicked":"",//本新闻点击数
							"ntoplevel":"",//本新闻置顶等级
							"nvisiable":"",//本新闻首页显示boolean值
							"ndate":"",//本新闻添加日期
							"nhref":"",//本新闻链接
							"ncontent":""//本新闻内容
								});
					this.store.insert(0,_r);
					var _key="";
					for(_key in oJson){
						if(_key=="nvisiable")
						{
							if(oJson[_key]=="true") oJson[_key]=true;
							else  oJson[_key]=false;
						}
						_r.set(_key,oJson[_key])
					};
					this.inserted.push(_r);//添加的数据push进inserted数组中
					this.startEditing(0,4);
			
		
		},
		
		onUpdateWinSubmit:function(_win,_oJson){
			
			if(_win.formPanel.getForm().isDirty())
				Ext.Msg.confirm("提示","你已经修改数据,提交并关闭编辑窗口?",function(_btn){
															if(_btn=="yes")
															{
																alert("dfdf");
																var selModel = this.getSelectionModel();
																var record = selModel.getSelected();
																var _key="";
																for(_key in _oJson)
																{
																	record.set(_key,_oJson[_key]);
																};
																_win.close_Ctrl();
															}
														},this);
			
			else
				Ext.Msg.confirm("提示","你还未修改数据,你需要关闭吗?",function(_btn){
															if(_btn=="yes")
																this.close_Ctrl();
														},_win);
		},
		onSelectedAction:function(){		//combobox选着查询
	
				var _cid =this.categoryCombobox.getValue();
				//this.store.baseparams=
				Ext.apply(this.store.baseParams,{categoryid:_cid});
			
				this.store.reload({params:{start:0,limit:5}});
		
		},
		disableWidget:function(){//对保存按钮与本grid中的categoryCombobox的disable/enable
			var modified =this.getStore().modified;//有脏数据，保持按钮enable，categoryCombobox disable
			
			if(modified.length>0)
			{
				//alert("length="+modified.length);
				
				Ext.getCmp('save').enable();
				
				this.categoryCombobox.disable();
				return ;
			}
			Ext.getCmp('save').disable();
			this.categoryCombobox.enable();
		}
		
})

/*********全局变量*******************************/
CategoryListURL_GLOBAL="../admin/getSCategoryList.action";
NewsListURL_GLOBAL="../admin/newsList.action";